﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Agile.Engine.Data;
using System.Web;


namespace Fis.Web.Rules
{
    public class CommonRule
    {
        /// <summary>
        /// 取服务帐套信息
        /// </summary>
        /// <param name="bookid"></param>
        /// <returns></returns>
        public DataTable ServiceBook(string bookid)
        {
            var sda = new Agile.Engine.Data.DataAccess() { Context = DataContext.Get("ServiceDataContext"), TableName = "TBOOK" };
            return sda.Query(string.Format("SBOOKID='{0}'", bookid));
        }

        public void ResetServicePassword(string bookid, string pwd, string year = null)
        {
            var sda = new Agile.Engine.Data.DataAccess() { Context = DataContext.Get("ServiceDataContext"), TableName = "TCUSTOM" };
            var data = sda.Query(string.Format("SBOOKID='{0}'", bookid));
            data.Rows[0]["FBOOKPWD"] = pwd;
            sda.Update(data.Rows[0]);
        }

        public void ResetAdminPassword(string bookid, string pwd, string year = null)
        {
            var data = DefaultBook(bookid);

            ///没有创建帐套
            if (data == null)
                return;

            var sdf = BookRealPath(bookid, year ?? data["FYEAR"].ToString());

            ///帐套不存在
            if (!System.IO.File.Exists(sdf))
                return;

            var dc = DataContext.Get("BookDataContext");
            SwitchConnection(dc, bookid, year ?? data["FYEAR"].ToString());

            dc.DefaultModel.ExecuteNonQuery(
                string.Format("UPDATE TUSER SET FPASSWORD='{0}',SINDEXDATE=GETDATE() WHERE SID='_default_superuser'", pwd));
        }

        /// <summary>
        /// 取默认服务账套信息
        /// </summary>
        /// <param name="bookid"></param>
        /// <returns></returns>
        public DataRow DefaultBook(string bookid)
        {
            var data = ServiceBook(bookid);
            var def = data.Select("FDEFAULT='1'");
            if (def.Length > 0)
            {
                return def[0];
            }
            return null;
        }

        /// <summary>
        /// 是否默认帐套
        /// </summary>
        /// <param name="bookid"></param>
        /// <returns></returns>
        public bool HasDefaultBook(string bookid)
        {
            return DefaultBook(bookid) != null;
        }

        /// <summary>
        /// 客户信息
        /// </summary>
        /// <param name="bookid"></param>
        /// <returns></returns>
        public DataRow CustomInfo(string bookid)
        {
            var sda = new Agile.Engine.Data.DataAccess() { Context = DataContext.Get("ServiceDataContext"), TableName = "TCUSTOM" };
            var data = sda.Query(string.Format("SBOOKID='{0}'", bookid));
            if (data.Rows.Count > 0)
                return data.Rows[0];
            return null;
        }

        /// <summary>
        /// 保存帐套创建信息
        /// </summary>
        /// <param name="bookid"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public bool SaveCreateBookInfo(string bookid, string year)
        {
            var sda = new Agile.Engine.Data.DataAccess() { Context = DataContext.Get("ServiceDataContext"), TableName = "TBOOK" };
            sda.Context.DefaultModel.ExecuteNonQuery("UPDATE TBOOK SET FDEFAULT='0' WHERE SBOOKID='" + bookid + "'");
            var data = sda.GetData(string.Format("{0}-{1}", bookid, year));
            bool isNew = false;
            if (data.Rows.Count == 0)
            {
                data.Rows.Add(data.NewRow());
                data.Rows[0]["SID"] = string.Format("{0}-{1}", bookid, year);
                isNew = true;
            }

            data.Rows[0]["SBOOKID"] = data.Rows[0]["FBOOKID"] = bookid;
            data.Rows[0]["FYEAR"] = year;
            data.Rows[0]["FDEFAULT"] = "1";

            if (isNew)
                sda.AddNew(data.Rows[0]);
            else
                sda.Update(data.Rows[0]);
            return true;
        }



        /// <summary>
        /// 帐套主管验证
        /// </summary>
        /// <param name="bookid"></param>
        /// <param name="info"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public bool IsCustomAdmin(string bookid, string info, string pwd)
        {
            var sda = new Agile.Engine.Data.DataAccess() { Context = DataContext.Get("ServiceDataContext"), TableName = "TCUSTOM" };
            var data = sda.Query(string.Format("SBOOKID='{0}' AND FCONTRACT='{1}' AND FBOOKPWD='{2}'", bookid, info, pwd));
            return data.Rows.Count > 0;
        }

        /// <summary>
        /// 切换帐套链接
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="bookid"></param>
        /// <param name="year"></param>
        public void SwitchConnection(DataContext dc, string bookid, string year)
        {
            dc.ResetConnString(string.Format(dc.GetConnString, bookid, year));
        }

        /// <summary>
        /// 帐套实际路径
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="bookid"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        public string BookRealPath(string bookid, string year)
        {
            var dc = DataContext.Get("BaseDataContext");
            return System.IO.Path.Combine(dc.GetConnString, "Books", bookid, string.Format("{0}-{1}.sdf", bookid, year));
        }

        public string NullYear(string bookid)
        {
            var book = DefaultBook(bookid);
            if (book != null)
            {
                return book["FYEAR"].ToString();
            }
            return DateTime.Now.Year.ToString();
        }

        /// <summary>
        /// TXTRA FXTRA5 = 1 为删除信息
        /// TXTRA FXTRA5 = 2 为反初始化,反结帐 table=UNREST sid对应期间,反初始化为0，反结帐为对应期间
        /// TXTRA FXTRA5 = 3 覆盖导入，其他客户端需要重新同步 table 表所有数据
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="table"></param>
        /// <param name="sid"></param>
        public void UpdateDeleteInfo(DataContext dc, string table, string sid, string sbook, int type = 1)
        {
            DataAccess da = new DataAccess() { Context = dc, TableName = "TXTRA" };
            var data = da.GetNewData();
            data.Rows[0]["SID"] = Guid.NewGuid().ToString();
            data.Rows[0]["FXTRA1"] = table;
            data.Rows[0]["FXTRA2"] = sid;
            data.Rows[0]["FXTRA5"] = type;
            data.Rows[0]["SINDEXDATE"] = DateTime.Now;
            data.Rows[0]["SBOOKID"] = sbook;
            da.AddNew(data.Rows[0]);
        }

    }
}
